package com.fa.dv.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import com.fa.dv.domain.Machinery;
import com.fa.dv.domain.Subject;
import com.fa.dv.service.IMachineryService;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
@Slf4j
public class MachineryReadListener implements ReadListener<Machinery> {
    private ArrayList<Machinery> cacheList = new ArrayList<>();
    private final int BATCH_COUNT = 3;
    private IMachineryService machineryService;

    public MachineryReadListener(IMachineryService machineryService){
        this.machineryService = machineryService;
    }

    /**
     * 读取到excel中每一行数据都会调用一次该方法
     */
    @Override
    public void invoke(Machinery machinery, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(machinery));
        cacheList.add(machinery);
        if (cacheList.size() >= BATCH_COUNT) {
            // 处理缓存数据
            saveData();
            // 清空缓存
            cacheList.clear();
        }
    }

    /**
     * 最后处理最后缓存中的数据
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cacheList.size());
        // 处理缓存数据的逻辑
        machineryService.saveBatch(cacheList);
        log.info("存储数据库成功！");
    }
}